/**
 * 
 */
package com.letoo.dragon.common.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * aes加密算法
 * 
 * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
 * 
 * @author dengjie
 *
 */
public class AESUtils {

    private static final Logger LOG = LoggerFactory.getLogger(AESUtils.class);

    private final static String IV = "0312032293271340";
    // 加解密统一使用的编码方式
    private final static String ENCODEING = "utf-8";

    public static String encrypt(String content, String secretKey) {
        try {
            if (secretKey == null) {
                return null;
            }
            if (secretKey.length() != 16) {
                return null;
            }
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = secretKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes(ENCODEING));
            return URLEncoder.encode(Base64.encodeBase64String(encrypted), ENCODEING);
        } catch (Exception e) {
            LOG.error("", e);
            return null;
        }

    }

    public static String decrypt(String content, String secretKey) {
        try {
            byte[] raw = secretKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] contentBytes = Base64.decodeBase64(URLDecoder.decode(content, ENCODEING));// 先用base64解密
            byte[] original = cipher.doFinal(contentBytes);
            String originalString = new String(original, ENCODEING);
            return originalString;
        } catch (Exception e) {
            LOG.error("", e);
            return null;
        }
    }

}
